from PySide6.QtWidgets import (QWidget, QHBoxLayout, QVBoxLayout,
                              QLabel, QPushButton, QCheckBox)
from PySide6.QtGui import QColor, QPainter, QPen
from PySide6.QtCore import Qt, Signal

class ColorSample(QWidget):
    """颜色样本显示组件 - 使用直接绘制确保颜色显示"""
    def __init__(self, color=None, size=30):
        super().__init__()
        self.size = size
        self.setFixedSize(size, size)
        # 设置最小尺寸确保可见
        self.setMinimumSize(size, size)
        self.color = color or QColor(255, 255, 255)
        # 添加调试信息
        print(f"ColorSample.__init__: 初始化颜色为 {self.color.name()} RGB({self.color.red()}, {self.color.green()}, {self.color.blue()})")

    def setColor(self, color):
        self.color = color
        # 添加调试信息
        print(f"ColorSample.setColor: 设置颜色为 {color.name()} RGB({color.red()}, {color.green()}, {color.blue()})")
        # 强制重绘
        self.update()

    def paintEvent(self, event):
        """直接绘制颜色，避免样式表冲突"""
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        # 绘制颜色填充
        painter.fillRect(self.rect(), self.color)

        # 绘制边框
        pen = QPen(QColor(51, 51, 51), 2)  # 深灰色边框
        painter.setPen(pen)
        painter.drawRect(self.rect().adjusted(1, 1, -1, -1))

        painter.end()
        print(f"ColorSample.paintEvent: 绘制颜色 {self.color.name()}")

class ColorTriggerItem:
    """颜色触发器数据模型"""
    def __init__(self, name, color, algorithm="RGB", tolerance=10, hsv_tolerances=None):
        self.name = name
        self.color = color  # RGB元组 (r, g, b)
        self.algorithm = algorithm  # "RGB" 或 "HSV"
        self.tolerance = tolerance  # RGB欧氏距离容差
        self.hsv_tolerances = hsv_tolerances or {"h": 15, "s": 30, "v": 40}  # HSV各通道容差
        self.enabled = True  # 是否启用
        self.detecting = False  # 是否正在检测

        # 触发行为设置
        self.trigger_mode = "press"  # 触发模式: "press"(按下), "release"(释放), "click"(点击)
        self.trigger_key = "left"  # 触发按键: "left"(左键), "right"(右键), "middle"(中键), 或键盘按键
        self.trigger_count = 0  # 触发次数: 0为无限触发
        self.trigger_interval = 100  # 触发间隔(毫秒)
        self.current_trigger_count = 0  # 当前已触发次数
        self.last_trigger_time = 0  # 上次触发时间

        # 颜色检测状态
        self.color_detected = False  # 当前是否检测到目标颜色
        self.hotkey_listener = None  # 全局热键监听器

        # 检测区域设置 - 智能避开准星
        self.detection_mode = "smart_around_center"  # 检测模式: "smart_around_center"(中心周围智能检测), "center"(屏幕中心), "custom"(自定义区域)
        self.detection_offset_x = 30  # 相对中心点的X偏移量(像素)
        self.detection_offset_y = 30  # 相对中心点的Y偏移量(像素)
        self.detection_area_width = 20  # 检测区域宽度
        self.detection_area_height = 20  # 检测区域高度
        self.detection_position = "top_right"  # 检测位置: "top_left", "top_right", "bottom_left", "bottom_right", "auto"

        # 颜色检测方法设置
        self.detection_method = "dominant_kmeans"  # 检测方法: "traditional"(传统), "kmeans"(K-Means聚类), "hybrid"(混合), "dominant_kmeans"(主要颜色K-Means)
        self.kmeans_clusters = 3  # K-Means聚类数量
        self.confidence_threshold = 0.3  # 最小置信度阈值
        self.last_detection_info = {}  # 最后检测信息

        # 主要颜色检测区域设置
        self.dominant_region_size = 200  # 主要颜色检测区域大小（正方形边长，像素）
        self.dominant_center_offset_x = 0  # 相对屏幕中心的X偏移（像素）
        self.dominant_center_offset_y = 0  # 相对屏幕中心的Y偏移（像素）

        # 持续触发状态
        self.hotkey_pressed = False  # 触发热键是否被按下
        self.continuous_timer = None  # 持续触发定时器
        self.continuous_thread = None  # 持续触发线程
        self.stop_continuous = False  # 停止持续触发的标志

class ColorTriggerItemWidget(QWidget):
    """颜色触发器列表项组件"""
    # 自定义信号
    editClicked = Signal(int)  # 编辑按钮点击信号
    deleteClicked = Signal(int)  # 删除按钮点击信号
    settingsClicked = Signal(int)  # 设置按钮点击信号（快捷键等）
    detectionAreaClicked = Signal(int)  # 检测区域设置按钮点击信号
    enabledChanged = Signal(int, bool)  # 启用状态变化信号
    detectingChanged = Signal(int, bool)  # 检测状态变化信号

    def __init__(self, item, index):
        super().__init__()
        self.item = item
        self.index = index
        self.setup_ui()

    def setup_ui(self):
        layout = QHBoxLayout(self)
        layout.setContentsMargins(5, 5, 5, 5)

        # 启用/禁用复选框
        self.enabled_check = QCheckBox()
        self.enabled_check.setChecked(self.item.enabled)
        self.enabled_check.stateChanged.connect(self.on_enabled_changed)
        layout.addWidget(self.enabled_check)

        # 颜色样本
        print(f"ColorTriggerItemWidget: 创建颜色样本，原始颜色: {self.item.color}")
        color_obj = QColor(*self.item.color)
        print(f"ColorTriggerItemWidget: QColor对象: {color_obj.name()} RGB({color_obj.red()}, {color_obj.green()}, {color_obj.blue()})")
        self.color_sample = ColorSample(color_obj)
        layout.addWidget(self.color_sample)

        # 信息区域
        info_layout = QVBoxLayout()
        self.name_label = QLabel(self.item.name)
        self.name_label.setStyleSheet("font-weight: bold;")

        if self.item.algorithm == "RGB":
            algo_text = f"RGB (容差: {self.item.tolerance})"
        else:
            h, s, v = self.item.hsv_tolerances.values()
            algo_text = f"HSV (H±{h}° S±{s}% V±{v}%)"

        self.algo_label = QLabel(algo_text)
        self.algo_label.setStyleSheet("color: gray; font-size: 10px;")

        info_layout.addWidget(self.name_label)
        info_layout.addWidget(self.algo_label)
        layout.addLayout(info_layout)

        layout.addStretch()

        # 检测按钮
        self.detect_btn = QPushButton("启动检测" if not self.item.detecting else "停止检测")
        self.detect_btn.setFixedWidth(80)
        self.detect_btn.clicked.connect(self.on_detecting_changed)
        layout.addWidget(self.detect_btn)

        # 编辑按钮
        self.edit_btn = QPushButton("编辑")
        self.edit_btn.setFixedWidth(60)
        self.edit_btn.clicked.connect(lambda: self.editClicked.emit(self.index))
        layout.addWidget(self.edit_btn)

        # 快捷键设置按钮
        self.settings_btn = QPushButton("快捷键")
        self.settings_btn.setFixedWidth(60)
        self.settings_btn.clicked.connect(lambda: self.settingsClicked.emit(self.index))
        layout.addWidget(self.settings_btn)

        # 删除按钮
        self.delete_btn = QPushButton("删除")
        self.delete_btn.setFixedWidth(60)
        self.delete_btn.clicked.connect(lambda: self.deleteClicked.emit(self.index))
        layout.addWidget(self.delete_btn)

    def on_enabled_changed(self, state):
        self.item.enabled = (state == Qt.Checked)
        self.enabledChanged.emit(self.index, self.item.enabled)

    def on_detecting_changed(self):
        self.item.detecting = not self.item.detecting
        self.detect_btn.setText("停止检测" if self.item.detecting else "启动检测")
        self.detectingChanged.emit(self.index, self.item.detecting)



